﻿using MesBSW.BLL.Mes;
using MesBSW.DAL.MesDB;
using MesBSW.Tools;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace MesBSW.View.Dialog.Mes
{
    public partial class SiteInfoDia : UIEditForm
    {

        #region "内部变量"
        private SqlSugarClient Db = SqlSugares.GetInstance();
        private SiteControler _ctrl = new SiteControler();
        private SiteInfo _curr_site = null;
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<StatusInfo> _status_list = new List<StatusInfo>();
        #endregion

        /// <summary>
        /// 无参数构造方法
        /// </summary>
        public SiteInfoDia()
        {
            InitializeComponent();
        }

        public SiteInfoDia(SiteInfo siteBean)
        {
            InitializeComponent();
            this._curr_site = siteBean;
            
        }

        #region "控件事件"
        private void SiteInfoDia_Load(object sender, EventArgs e)
        {
            this.InitParentCmbData();
            this.InitStatusCmbData();
            this.InitControlValue(this._curr_site);
        }

        private void rbnIsDel_Click(object sender, EventArgs e)
        {
            this.rbnIsDel.Checked = true;
            this.rbnNotDel.Checked = false;
        }

        private void rbnNotDel_Click(object sender, EventArgs e)
        {
            this.rbnIsDel.Checked = false;
            this.rbnNotDel.Checked = true;
        }

        private void rbnIsFinal_Click(object sender, EventArgs e)
        {
            this.rbnIsFinal.Checked = true;
            this.rbnNotFinal.Checked = false;
        }

        private void rbnNotFinal_Click(object sender, EventArgs e)
        {
            this.rbnIsFinal.Checked = false;
            this.rbnNotFinal.Checked = true;
        }

        private void chkBeginPoint_Click(object sender, EventArgs e)
        {
            if (this.chkBeginPoint.Checked)
            {
                this.chkEndPoint.Checked = false;
            }
        }

        private void chkEndPoint_Click(object sender, EventArgs e)
        {
            if (this.chkEndPoint.Checked)
            {
                this.chkBeginPoint.Checked = false;
            }
        }
        #endregion

        #region "内部方法"

        private void InitStatusCmbData()
        {
            this.cmbDefStatus.Items.Clear();
            this._status_list = this._ctrl.SearchAllProdStatus();

            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("id");
            tmpDt.Columns.Add("name");
            if (this._status_list != null)
            {
                foreach (var item in this._status_list)
                {
                    DataRow addRow = tmpDt.NewRow();
                    addRow["id"] = item.ID;
                    addRow["name"] = item.StatusValue;
                    tmpDt.Rows.Add(addRow);
                }
            }

            this.cmbDefStatus.DataSource = tmpDt;
            this.cmbDefStatus.ValueMember = "id";
            this.cmbDefStatus.DisplayMember = "name";
        }

        /// <summary>
        /// 界面读入时，初始化下拉列表
        /// </summary>
        private void InitParentCmbData()
        {
            this.cmbParent.Items.Clear();
            this._site_list = this._ctrl.SearchNotFinalStieInfo();

            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("id");
            tmpDt.Columns.Add("name");

            DataRow allRow = tmpDt.NewRow();
            allRow["id"] = 0;
            allRow["name"] = "根站点";
            tmpDt.Rows.Add(allRow);
            if (this._site_list != null)
            {
                foreach (var item in this._site_list)
                {
                    DataRow addRow = tmpDt.NewRow();
                    addRow["id"] = item.ID;
                    addRow["name"] = item.SiteName;
                    tmpDt.Rows.Add(addRow);
                }
            }

            this.cmbParent.DataSource = tmpDt;
            this.cmbParent.DisplayMember = "Name";
            this.cmbParent.ValueMember = "id";
            //查询部门
            string sql = $@"select * from base_dept where parent_id = 6";
            var list = Db.SqlQueryable<object>(sql).ToList();
            dynamic dylist = list;
            this.ComboBoxDepts.DisplayMember = "Key";
            this.ComboBoxDepts.ValueMember = "Value";

            for (int i = 0; i < dylist.Count; i++)
            {
                this.ComboBoxDepts.Items.Add(new KeyValuePair<string, int>(dylist[i].dept_name, dylist[i].id));
            }
        }

        /// <summary>
        /// 根据传入的站点信息设置界面中控件的值
        /// </summary>
        /// <param name="siteBean"></param>
        private void InitControlValue(SiteInfo siteBean)
        {
            if (siteBean != null)
            {
                dynamic result = Db.Context.SqlQueryable<object>($@"select dept_name from base_dept where id = {siteBean.deptId}").ToList().FirstOrDefault();
                string dept_name = result?.dept_name.ToString();
                int index = this.ComboBoxDepts.FindStringExact(dept_name);
                if(index != -1)
                {
                    this.ComboBoxDepts.SelectedIndex = index;
                }
                this.txtSiteCode.Tag = siteBean.ID;
                this.txtSiteCode.Text = siteBean.SiteCode != null ? siteBean.SiteCode : "";
                this.txtSiteName.Text = siteBean.SiteName != null ? siteBean.SiteName : "";
                this.txtSiteSN.Text = siteBean.SiteShortName != null ? siteBean.SiteShortName : "";
                if (this._site_list != null)
                {
                    if (siteBean.ParentID == 0)
                    {
                        this.cmbParent.Text = "根站点";
                    }
                    else
                    {
                        var query = this._site_list.Where(s => s.ID == siteBean.ParentID);
                        if (query != null && query.Count() > 0)
                        {
                            this.cmbParent.Text = query.First().SiteName;
                        }
                    }
                }

                if (this._status_list != null)
                {
                    if (siteBean.DefStatus.HasValue && (siteBean.DefStatus ?? 0) > 0)
                    {
                        var query = this._status_list.Where(s => s.ID == siteBean.DefStatus);
                        if (query != null && query.Count() > 0)
                        {
                            this.cmbDefStatus.Text = query.First<StatusInfo>().StatusValue;
                        }
                    }
                }

                if (siteBean.CalPoint != null && siteBean.CalPoint.Equals("B"))
                {
                    this.chkBeginPoint.Checked = true;
                    this.chkEndPoint.Checked = false;
                }
                else if (siteBean.CalPoint != null && siteBean.CalPoint.Equals("E"))
                {
                    this.chkBeginPoint.Checked = false;
                    this.chkEndPoint.Checked = true;
                }
                else
                {
                    this.chkBeginPoint.Checked = false;
                    this.chkEndPoint.Checked = false;
                }

                if (siteBean.IsDel == 1)
                {
                    this.rbnIsDel.Checked = true;
                    this.rbnNotDel.Checked = false;
                }
                else
                {
                    this.rbnIsDel.Checked = false;
                    this.rbnNotDel.Checked = true;
                }

                if (siteBean.IsFinal == 1)
                {
                    this.rbnIsFinal.Checked = true;
                    this.rbnNotFinal.Checked = false;
                }
                else
                {
                    this.rbnIsFinal.Checked = false;
                    this.rbnNotFinal.Checked = true;
                }

                if (siteBean.ID <= 0)
                {
                    this.txtSiteCode.Enabled = true;
                    this.txtSiteName.Enabled = true;
                }
                else
                {
                    this.txtSiteCode.Enabled = false;
                    this.txtSiteName.Enabled = false;
                    this.cmbParent.Enabled = false;
                }
            }
            else
            {
                this.txtSiteCode.Tag = 0;
                this.txtSiteCode.Text = "";
                this.txtSiteName.Text = "";
                this.txtSiteSN.Text = "";
                this.cmbParent.SelectedValue = siteBean.ParentID;
                this.rbnNotDel.Checked = true;
                this.rbnIsDel.Checked = false;
                this.txtSiteCode.Enabled = true;
                this.txtSiteName.Enabled = true;
                this.cmbParent.Enabled = true;
            }
            this.cmbParent.Refresh();
        }

        /// <summary>
        /// 从界面各控件中取值组成站点信息
        /// </summary>
        /// <returns></returns>
        private SiteInfo InitSiteInfo()
        {
            int tmpInt = 0;
            SiteInfo siteBean = new SiteInfo();
            siteBean.ID = int.Parse(this.txtSiteCode.Tag.ToString());
            siteBean.SiteCode = this.txtSiteCode.Text.Trim();
            siteBean.SiteName = this.txtSiteName.Text.Trim();
            siteBean.SiteShortName = this.txtSiteSN.Text.Trim();
            siteBean.ParentID = int.Parse(this.cmbParent.SelectedValue.ToString());
            siteBean.IsDel = this.rbnIsDel.Checked == true ? 1 : 0;
            siteBean.IsFinal = this.rbnIsFinal.Checked == true ? 1 : 0;
            if (this.cmbDefStatus.SelectedValue != null)
            {
                siteBean.DefStatus = int.TryParse(this.cmbDefStatus.SelectedValue.ToString(), out tmpInt) ? int.Parse(this.cmbDefStatus.SelectedValue.ToString()) : 0;
            }
            else
            {
                siteBean.DefStatus = 0;
            }
            siteBean.CalPoint = this.chkBeginPoint.Checked ? "B" : this.chkEndPoint.Checked ? "E" : "";

            return siteBean;
        }

        private string CheckSiteInfo(SiteInfo siteInfo)
        {
            string errStr = "";
            if (siteInfo != null)
            {
                if (siteInfo.IsFinal == 0)
                {
                    //if (siteInfo.DefStatus != 0 && siteInfo.ParentID == 0)//siteInfo.DefStatus.HasValue && siteInfo.DefStatus > 0
                    //{
                    //    errStr = "该站点为父站点，不需要有默认状态！";
                    //}
                    if (siteInfo.CalPoint != null && siteInfo.CalPoint.Equals("B"))
                    {
                        errStr = "该站点为父站点，不能设为有效时间的开始点！";
                    }
                    else if (siteInfo.CalPoint != null && siteInfo.CalPoint.Equals("E"))
                    {
                        errStr = "该站点为父站点，不能设为有效时间的结束点！";
                    }
                }
            }
            return errStr;
        }
        #endregion

        private void btnOK_Click(object sender, EventArgs e)
        {
            SiteInfo tmpBean = this.InitSiteInfo();
            tmpBean.CreateDate = this._curr_site.CreateDate;
            tmpBean.CreateUser = this._curr_site.CreateUser;
            tmpBean.deptId = 13;
            if (tmpBean != null)
            {
                if (tmpBean.SiteCode.Equals("") || tmpBean.SiteName.Equals("") || tmpBean.SiteShortName.Equals(""))
                {
                    UIMessageBox.ShowWarning("站点代号、站点名称、站点简称都不可以为空，保存失败！");
                }
                else
                {
                    string errStr = this.CheckSiteInfo(tmpBean);
                    if (errStr != null && errStr.Length > 0)
                    {
                        UIMessageBox.ShowError(errStr);
                    }
                    else
                    {
                        try
                        {
                            int count = 0;
                            if (tmpBean.ID <= 0)
                            {
                                count = this._ctrl.InsertSiteInfo(tmpBean);
                            }
                            else
                            {
                                Boolean isDiff = EntityTools.IsDiffForValue(this._curr_site, tmpBean);
                                if (isDiff == false)
                                {
                                    string beforeStr = EntityTools.GetPropNameAndValue(this._curr_site);
                                    string afterStr = EntityTools.GetPropNameAndValue(tmpBean);
                                    count = this._ctrl.UpdateSiteInfo(tmpBean, beforeStr, afterStr);
                                }
                            }

                            if (count > 0)
                            {
                                UIMessageBox.ShowSuccess("站点信息更新成功！");
                            }
                            else
                            {
                                UIMessageBox.ShowSuccess("站点信息更新失败！");
                            }
                        }
                        catch (Exception ex)
                        {
                            UIMessageBox.ShowError("站点信息更新失败！" + "\r\n" + ex.Message);
                        }
                    }
                }
            }
            else
            {
                UIMessageBox.ShowError("没有任何可以保存的站点信息！");
            }
        }
    }
}
